package swings.buttons;

import change.ItemColorChange;
import controllers.CommonButtonControl;
import utils.ImageUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

/**
 * @version V1.0
 * @Title: 通用button，重写了构造方法
 * @Package
 * @Description:
 * @author: GaleBlade
 * @date:
 */
public class CommonButton extends JButton {

    public CommonButtonControl mouse;
    public int status = 1;
    private BufferedImage img;

    /**
     * 构造方法
     */
    public CommonButton(BufferedImage img, int x, int y, int width, int height){
        this.img = img;
        super.setContentAreaFilled(false);
        super.setIcon(new ImageIcon(ItemColorChange.change(img)));
        super.setBorder(null);
        super.setBounds(x,y,width,height);
        //添加鼠标事件
        mouse = new CommonButtonControl(this,img);
        super.addMouseListener(mouse);
    }

    public void removeButtonControl(){
        super.removeMouseListener(mouse);
    }

    /**
     * 按住处理方法
     */
    public void hold(){
        this.status = 1;
        super.setIcon(new ImageIcon(img));
    }

    /**
     * 松开处理方法
     */
    public void release(){
        this.status = 0;
        super.setIcon(ImageUtils.nullImg);
    }

    public int getStatus(){
        return this.status;
    }

    /**
     * 添加hold监听器
     */
    public void setHoldListener(){
        this.addActionListener(new holdListener());
    }

    /**
     * hold监听器
     */
    private class holdListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            //根据按钮内的状态设置是否开启功能
            if (status == 0){
                hold();
            }else {
                release();
            }
        }
    }

    /**
     * 添加hold监听器
     */
    public void setMethodListener(){
        this.addActionListener(new methodListener());
    }

    /**
     * hold监听器
     */
    private class methodListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            //根据按钮内的状态设置是否开启功能
            if (status == 0){
                status = 1;
                setIcon(ImageUtils.post);
            }else {
                status = 0;
                setIcon(ImageUtils.get);
            }
        }
    }

}
